package cn.cmcc.online.smsapi.ui.presenter;

import android.content.Context;
import android.text.TextUtils;

import org.json.JSONObject;

import java.util.List;

import cn.cmcc.online.smsapi.ui.manager.IDataCallback;
import cn.cmcc.online.smsapi.ui.model.FlightData;
import cn.cmcc.online.smsapi.ui.model.MetaData;
import cn.cmcc.online.smsapi.ui.model.TableData;
import cn.cmcc.online.smsapi.ui.model.TransportSelectInfo;
import cn.cmcc.online.smsapi.ui.util.DataExchangeProxy;
import cn.cmcc.online.smsapi.ui.util.DataUtil;

public class FlightPresenterImpl extends FlightPresenter {

    private Context mContext = null;
    private int mCurrentFlightIndex = 0;
    private FlightData mCurrentFlightData = null;
    private MetaData mMetaData = null;

    public FlightPresenterImpl(Context context) {
        mContext = context;
    }

    private void showBody() {
        mCurrentFlightData = DataUtil.getFlightData(cardData, mCurrentFlightIndex);
        if (mCurrentFlightData != null) {
            vista.showBody(mCurrentFlightData, mMetaData);
        }
    }

    private void showBodyAndUpdate() {
        showBody();
        vista.updateBottom();
        DataExchangeProxy.getInstance().updateCardInfo(cardData);
    }

    @Override
    public void bind(JSONObject data) {
        super.bind(data);
        mMetaData = DataUtil.getMetaData(cardData);

        showBody();
        if (DataUtil.getMainData(cardData).length() > 1) {
            vista.enableFlightSelect(mMetaData);
        } else {
            vista.disableFlightSelect();
        }

        List<TableData> dataList = DataUtil.getTableList(cardData);
        if (dataList != null && dataList.size() > 0) {
            vista.showTable(dataList);
        }

        String tips = DataUtil.getNote(cardData);
        if (!TextUtils.isEmpty(tips) && !tips.equals("null")) {
            vista.showNote(tips);
        }
    }

    @Override
    public void selectFlight(int index) {
        mCurrentFlightIndex = index;
        showBodyAndUpdate();
    }

    @Override
    public void queryFlightNumber() {
        vista.showFlightSelect(new TransportSelectInfo(cardData, TransportSelectInfo.TRANSPORT_FLIGHT), mCurrentFlightIndex);
    }

    @Override
    public void completeFlightInfo() {
        if (mCurrentFlightData != null) {
            mCurrentFlightData.setReceiveTime(DataUtil.getReceiveTime(cardData));
            DataExchangeProxy.getInstance().getFlightInfo(mCurrentFlightData, new IDataCallback<FlightData>() {
                @Override
                public void onReady(int status, FlightData data) {
                    if (status == IDataCallback.SUCCESS) {
                        mCurrentFlightData = data;
                        DataUtil.updateFlightJSONObject(cardData, mCurrentFlightData);
                        showBodyAndUpdate();
                    }
                }
            });
        }
    }
}
